package org.jeecg.modules.door.controller;

import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.door.entity.LwgyDoorInfo;
import org.jeecg.modules.door.service.ILwgyDoorInfoService;
import org.jeecg.modules.door.stocket.SocketServer;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 门锁管理
 * @Author: jeecg-boot
 * @Date:   2024-02-26
 * @Version: V1.0
 */
@Api(tags="门锁管理")
@RestController
@RequestMapping("/door/lwgyDoorInfo")
@Slf4j
public class LwgyDoorInfoController extends JeecgController<LwgyDoorInfo, ILwgyDoorInfoService> {
	@Autowired
	private ILwgyDoorInfoService lwgyDoorInfoService;
	
	/**
	 * 分页列表查询
	 *
	 * @param lwgyDoorInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "门锁管理-分页列表查询")
	@ApiOperation(value="门锁管理-分页列表查询", notes="门锁管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(LwgyDoorInfo lwgyDoorInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<LwgyDoorInfo> queryWrapper = QueryGenerator.initQueryWrapper(lwgyDoorInfo, req.getParameterMap());
		Page<LwgyDoorInfo> page = new Page<LwgyDoorInfo>(pageNo, pageSize);
		IPage<LwgyDoorInfo> pageList = lwgyDoorInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param lwgyDoorInfo
	 * @return
	 */
	@AutoLog(value = "门锁管理-添加")
	@ApiOperation(value="门锁管理-添加", notes="门锁管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody LwgyDoorInfo lwgyDoorInfo) {
		lwgyDoorInfoService.save(lwgyDoorInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param lwgyDoorInfo
	 * @return
	 */
	@AutoLog(value = "门锁管理-编辑")
	@ApiOperation(value="门锁管理-编辑", notes="门锁管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody LwgyDoorInfo lwgyDoorInfo) {
		lwgyDoorInfoService.updateById(lwgyDoorInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "门锁管理-通过id删除")
	@ApiOperation(value="门锁管理-通过id删除", notes="门锁管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		lwgyDoorInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "门锁管理-批量删除")
	@ApiOperation(value="门锁管理-批量删除", notes="门锁管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.lwgyDoorInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "门锁管理-通过id查询")
	@ApiOperation(value="门锁管理-通过id查询", notes="门锁管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		LwgyDoorInfo lwgyDoorInfo = lwgyDoorInfoService.getById(id);
		if(lwgyDoorInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(lwgyDoorInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param lwgyDoorInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyDoorInfo lwgyDoorInfo) {
        return super.exportXls(request, lwgyDoorInfo, LwgyDoorInfo.class, "门锁管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyDoorInfo.class);
    }


	 /**
	  *   读取鲁维门锁信息
	  *
	  * @param lwgyDoorInfo
	  * @return
	  */
	 @AutoLog(value = "门锁管理-读取鲁维门锁信息（测试）")
	 @ApiOperation(value="门锁管理-读取鲁维门锁信息（测试）", notes="门锁管理-读取鲁维门锁信息（测试）")
	 @PutMapping(value = "/doorInfoTest")
	 public Result<?> doorInfoTest(@RequestBody LwgyDoorInfo lwgyDoorInfo) {
	 	System.out.println("num==========================================");
	 	System.out.println("number:"+lwgyDoorInfo.getLockNumber());
	 	String number = lwgyDoorInfo.getLockNumber();
		 SocketServer ss = new SocketServer();
		 String[] response = ss.findInfoByOther(number);
		if(oConvertUtils.isNotEmpty(response)){
			lwgyDoorInfo.setLockStatus(response[5]);//锁状态
			lwgyDoorInfo.setUnlockingMethod(response[6]);//开锁方式
			lwgyDoorInfo.setClosingStatus(response[7]);//关门状态
			//response[8]电池欠压力，文档没有给出解析
			String finalNumber=response[9]+response[10]+response[11]+response[12]+response[13];
			System.out.println(finalNumber);
			//int finalUnlockNumber = Integer.parseInt(finalNumber, 16);
			long finalUnlockNumber = Long.parseLong(finalNumber, 16);
			lwgyDoorInfo.setFinalUnlock(finalUnlockNumber+"");//最后开锁卡号
			int voltageNumber = Integer.parseInt(response[14], 16);
			double result = (double)voltageNumber / 10;
			lwgyDoorInfo.setVoltage(result+"V");//电池电压//D13电池电压 1位定点小数，例如6.1V ，表示为十六进制值：3d；
			int temperatureNumber = Integer.parseInt(response[15], 16);
			lwgyDoorInfo.setTemperature(temperatureNumber+"");//温度  32℃ 表示成 0x20。
			int timeNumber = Integer.parseInt(response[16]+response[17], 16);
			 lwgyDoorInfo.setTimes(timeNumber+"");//D15D16 开关锁次数统计：包括开锁、关锁的总次数，用于统计开关锁的频度。1300次 = 0x0546 = D15(05)D16(56).
			lwgyDoorInfo.setStatus("0");
			lwgyDoorInfoService.saveOrUpdate(lwgyDoorInfo);
			return Result.OK("添加成功！");
		}else{
			return Result.OK("添加失败！");
		}

	 }




 }
